import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
// import 'package:intl/intl.dart';
import '../../providers/bill_provider.dart';
import '../../providers/restaurant_provider.dart';
import '../../providers/product_provider.dart';
import '../../models/bill.dart';
import '../../models/bill_item.dart';
import '../../models/restaurant.dart';
import '../../models/product.dart';
import '../../core/app_theme.dart';
import '../../core/snackbar_helper.dart';
import '../../widgets/date_time_picker.dart';

class AddEditBillScreen extends StatefulWidget {
  final int? billId;

  const AddEditBillScreen({super.key, this.billId});

  @override
  State<AddEditBillScreen> createState() => _AddEditBillScreenState();
}

class _AddEditBillScreenState extends State<AddEditBillScreen> {
  late DateTime _customDate;
  Restaurant? _selectedRestaurant;
  List<BillItem> _billItems = [];
  final TextEditingController _notesController = TextEditingController();
  bool _isLoading = true;
  
  // 价格快照映射：productId -> 快照价格
  final Map<int, double> _priceSnapshots = {};

  @override
  void initState() {
    super.initState();
    _customDate = DateTime.now();
    _initializeData();
  }

  Future<void> _initializeData() async {
    if (widget.billId != null) {
      await _loadBillForEditing();
    } else {
      setState(() {
        _isLoading = false;
      });
    }
  }

  Future<void> _loadBillForEditing() async {
    try {
      final billProvider = Provider.of<BillProvider>(context, listen: false);
      final bill = await billProvider.getBillById(widget.billId!);
      
      if (bill != null) {
        final restaurantProvider = Provider.of<RestaurantProvider>(context, listen: false);
        await restaurantProvider.loadRestaurants();
        
        final restaurants = restaurantProvider.restaurants;
        _selectedRestaurant = restaurants.firstWhere(
          (r) => r.id == bill.restaurantId,
          orElse: () => Restaurant(id: -1, name: bill.restaurantName),
        );
        
        _billItems = await billProvider.getBillItems(bill.id!);
        _notesController.text = bill.notes ?? '';
        _customDate = bill.customDate ?? bill.billDate;
        
        // 为现有商品创建价格快照
        for (var item in _billItems) {
          _priceSnapshots[item.productId] = item.unitPrice;
        }
      }
    } catch (e) {
      SnackbarHelper.showError(context, '加载账单失败: $e');
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  // 计算总金额
  double get _totalAmount {
    return _billItems.fold(0.0, (sum, item) => sum + item.subtotal);
  }

  // 保存价格快照
  void _createPriceSnapshot(Product product) {
    _priceSnapshots[product.id!] = product.currentPrice;
  }

  // 获取保护价格（优先使用快照价格）
  double _getProtectedPrice(Product product) {
    return _priceSnapshots[product.id!] ?? product.currentPrice;
  }

  Future<void> _saveBill() async {
    if (_selectedRestaurant == null) {
      SnackbarHelper.showError(context, '请选择饭店');
      return;
    }

    if (_billItems.isEmpty) {
      SnackbarHelper.showError(context, '请添加至少一个商品');
      return;
    }

    try {
      final billProvider = Provider.of<BillProvider>(context, listen: false);
      final now = DateTime.now();

      final bill = Bill(
        id: widget.billId,
        restaurantId: _selectedRestaurant!.id!,
        restaurantName: _selectedRestaurant!.name,
        totalAmount: _totalAmount,
        customDate: _customDate, // 使用用户选择的时间
        billDate: _customDate,   // 这里也使用用户选择的时间，而不是当前时间
        status: 'pending',
        notes: _notesController.text.isEmpty ? null : _notesController.text,
        createdAt: now,          // 系统创建时间仍然是当前时间
        updatedAt: now,
      );

      if (widget.billId == null) {
        // 创建新账单
        await billProvider.createBill(bill, _billItems);
        SnackbarHelper.showSuccess(context, '账单创建成功');
      } else {
        // 更新现有账单
        await billProvider.updateBill(bill);
        
        // 更新账单项
        final oldItems = await billProvider.getBillItems(widget.billId!);
        for (var item in oldItems) {
          await billProvider.deleteBillItem(item.id!);
        }
        for (var item in _billItems) {
          await billProvider.addBillItem(item.copyWith(billId: widget.billId!));
        }
        
        SnackbarHelper.showSuccess(context, '账单更新成功');
      }

      Navigator.of(context).pop(true);
    } catch (e) {
      SnackbarHelper.showError(context, '保存失败: $e');
    }
  }
  // 添加商品到账单
  void _addProductToBill(Product product, int quantity) {
    // 创建价格快照
    _createPriceSnapshot(product);
    final protectedPrice = _getProtectedPrice(product);
    
    setState(() {
      // 检查是否已存在该商品
      final existingIndex = _billItems.indexWhere(
        (item) => item.productId == product.id
      );
      
      if (existingIndex != -1) {
        // 更新现有商品数量
        final existingItem = _billItems[existingIndex];
        _billItems[existingIndex] = existingItem.copyWith(
          quantity: existingItem.quantity + quantity,
          subtotal: protectedPrice * (existingItem.quantity + quantity),
        );
      } else {
        // 添加新商品
        final newItem = BillItem(
          billId: widget.billId ?? 0,
          productId: product.id!,
          productName: product.name,
          productSpec: product.spec,
          unitPrice: protectedPrice, // 使用保护价格
          quantity: quantity,
          subtotal: protectedPrice * quantity,
        );
        _billItems.add(newItem);
      }
    });
    
    _updateTotalAmount();
  }

  // 更新商品数量
  void _updateItemQuantity(int index, int newQuantity) {
    if (newQuantity <= 0) {
      // 数量为0时移除商品
      _deleteBillItem(index);
    } else {
      setState(() {
        final item = _billItems[index];
        _billItems[index] = item.copyWith(
          quantity: newQuantity,
          subtotal: item.unitPrice * newQuantity,
        );
      });
      _updateTotalAmount();
    }
  }

  // 删除商品
  void _deleteBillItem(int index) {
    setState(() {
      final removedItem = _billItems.removeAt(index);
      // 移除对应的价格快照
      _priceSnapshots.remove(removedItem.productId);
    });
    _updateTotalAmount();
  }

  // 更新总金额并通知Provider
  void _updateTotalAmount() {
    // 这里会触发界面重建，所以不需要额外操作
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(
          widget.billId == null ? '新建账单' : '编辑账单',
          style: AppTheme.titleLarge,
        ),
        actions: [
          IconButton(
            icon: const Icon(Icons.save),
            onPressed: _saveBill,
            tooltip: '保存',
          ),
        ],
      ),
      body: _isLoading
          ? const Center(child: CircularProgressIndicator())
          : _buildContent(),
    );
  }

  Widget _buildContent() {
    return Column(
      children: [
        // 时间选择和饭店选择区域
        Card(
          margin: const EdgeInsets.all(16),
          child: Padding(
            padding: const EdgeInsets.all(16),
            child: Column(
              children: [
                // 时间选择器
                DateTimePicker(
                  initialDate: _customDate,
                  onDateSelected: (selectedDate) {
                    setState(() {
                      _customDate = selectedDate;
                    });
                  },
                ),
                const SizedBox(height: 16),
                _buildRestaurantDropdown(),
              ],
            ),
          ),
        ),

        // 商品列表区域
        Expanded(
          child: _billItems.isEmpty
              ? _buildEmptyState()
              : ListView.builder(
                  itemCount: _billItems.length,
                  itemBuilder: (context, index) => _buildBillItem(_billItems[index], index),
                ),
        ),

        // 底部汇总和操作区域
        _buildBottomPanel(),
      ],
    );
  }

  Widget _buildEmptyState() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          const Icon(Icons.shopping_cart_outlined, size: 64, color: Colors.grey),
          const SizedBox(height: 16),
          const Text(
            '暂无商品',
            style: TextStyle(fontSize: 18, color: Colors.grey),
          ),
          const SizedBox(height: 8),
          ElevatedButton.icon(
            onPressed: _selectedRestaurant != null ? _showProductSelectionDialog : null,
            icon: const Icon(Icons.add),
            label: const Text('添加商品'),
          ),
        ],
      ),
    );
  }

  Widget _buildBottomPanel() {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.grey[50],
        border: Border(top: BorderSide(color: Colors.grey[300]!)),
      ),
      child: Column(
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              const Text(
                '总计:',
                style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
              ),
              Text(
                '¥${_totalAmount.toStringAsFixed(2)}',
                style: const TextStyle(
                  fontSize: 20,
                  fontWeight: FontWeight.bold,
                  color: Colors.green,
                ),
              ),
            ],
          ),
          const SizedBox(height: 12),
          Row(
            children: [
              Expanded(
                child: OutlinedButton.icon(
                  onPressed: _selectedRestaurant != null ? _showProductSelectionDialog : null,
                  icon: const Icon(Icons.add),
                  label: const Text('添加商品'),
                ),
              ),
              const SizedBox(width: 8),
              Expanded(
                child: ElevatedButton.icon(
                  onPressed: _saveBill,
                  icon: const Icon(Icons.save),
                  label: Text(widget.billId == null ? '创建账单' : '更新账单'),
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildRestaurantDropdown() {
    return Consumer<RestaurantProvider>(
      builder: (context, restaurantProvider, child) {
        if (restaurantProvider.restaurants.isEmpty) {
          return const Text('暂无饭店，请先添加饭店');
        }

        return DropdownButtonFormField<Restaurant>(
          value: _selectedRestaurant,
          decoration: const InputDecoration(
            border: OutlineInputBorder(),
            labelText: '选择饭店',
          ),
          onChanged: (Restaurant? newValue) {
            setState(() {
              _selectedRestaurant = newValue;
              _billItems.clear();
              _priceSnapshots.clear();
            });
          },
          items: restaurantProvider.restaurants.map((Restaurant restaurant) {
            return DropdownMenuItem<Restaurant>(
              value: restaurant,
              child: Text(restaurant.name),
            );
          }).toList(),
        );
      },
    );
  }

  Widget _buildBillItem(BillItem item, int index) {
    return Card(
      margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
      child: ListTile(
        contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
        leading: CircleAvatar(
          backgroundColor: Colors.blue,
          child: Text(
            item.quantity.toString(),
            style: const TextStyle(color: Colors.white, fontWeight: FontWeight.bold),
          ),
        ),
        title: Text(
          item.productName,
          style: const TextStyle(fontWeight: FontWeight.bold),
        ),
        subtitle: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const SizedBox(height: 4),
            Text('规格: ${item.productSpec}'),
            const SizedBox(height: 2),
            Text('单价: ¥${item.unitPrice.toStringAsFixed(2)}'),
          ],
        ),
        trailing: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            Text(
              '¥${item.subtotal.toStringAsFixed(2)}',
              style: const TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.bold,
                color: Colors.green,
              ),
            ),
            const SizedBox(width: 8),
            PopupMenuButton<String>(
              onSelected: (action) => _handleItemAction(action, item, index),
              itemBuilder: (BuildContext context) => [
                const PopupMenuItem(
                  value: 'edit_quantity',
                  child: ListTile(
                    leading: Icon(Icons.edit),
                    title: Text('修改数量'),
                  ),
                ),
                const PopupMenuItem(
                  value: 'delete',
                  child: ListTile(
                    leading: Icon(Icons.delete, color: Colors.red),
                    title: Text('删除'),
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  void _handleItemAction(String action, BillItem item, int index) {
    switch (action) {
      case 'edit_quantity':
        _showQuantityDialog(item, index);
        break;
      case 'delete':
        _showDeleteDialog(index);
        break;
    }
  }

  void _showQuantityDialog(BillItem item, int index) {
    final TextEditingController quantityController = TextEditingController(
      text: item.quantity.toString()
    );
    
    showDialog(
      context: context,
      builder: (ctx) => AlertDialog(
        title: Text('修改数量 - ${item.productName}'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Text('当前数量: ${item.quantity}'),
            const SizedBox(height: 16),
            TextField(
              controller: quantityController,
              keyboardType: TextInputType.number,
              decoration: const InputDecoration(
                labelText: '新数量',
                border: OutlineInputBorder(),
                hintText: '输入0将删除此商品',
              ),
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(ctx).pop(),
            child: const Text('取消'),
          ),
          ElevatedButton(
            onPressed: () {
              final newQuantity = int.tryParse(quantityController.text) ?? 0;
              Navigator.of(ctx).pop();
              _updateItemQuantity(index, newQuantity);
            },
            child: const Text('确认'),
          ),
        ],
      ),
    );
  }

  void _showDeleteDialog(int index) {
    final item = _billItems[index];
    
    showDialog(
      context: context,
      builder: (ctx) => AlertDialog(
        title: const Text('确认删除'),
        content: Text('确定要删除"${item.productName}"吗？'),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(ctx).pop(),
            child: const Text('取消'),
          ),
          ElevatedButton(
            onPressed: () {
              Navigator.of(ctx).pop();
              _deleteBillItem(index);
            },
            style: ElevatedButton.styleFrom(backgroundColor: Colors.red),
            child: const Text('删除'),
          ),
        ],
      ),
    );
  }

  // 商品选择对话框
  void _showProductSelectionDialog() async {
    if (_selectedRestaurant == null) {
      SnackbarHelper.showError(context, '请先选择饭店');
      return;
    }

    try {
      final productProvider = Provider.of<ProductProvider>(context, listen: false);
      await productProvider.loadProductsByRestaurant(_selectedRestaurant!.id!);
      
      final products = productProvider.products;
      
      if (products.isEmpty) {
        SnackbarHelper.showError(context, '该饭店暂无商品');
        return;
      }

      Product? selectedProduct;
      int quantity = 1;

      await showDialog(
        context: context,
        builder: (ctx) => StatefulBuilder(
          builder: (context, setState) {
            final currentPrice = selectedProduct?.currentPrice ?? 0;
            final subtotal = currentPrice * quantity;
            
            return AlertDialog(
              title: const Text('添加商品'),
              content: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  DropdownButtonFormField<Product>(
                    decoration: const InputDecoration(
                      labelText: '选择商品',
                      border: OutlineInputBorder(),
                    ),
                    value: selectedProduct,
                    onChanged: (Product? newValue) {
                      setState(() => selectedProduct = newValue);
                    },
                    items: products.map((Product product) {
                      return DropdownMenuItem<Product>(
                        value: product,
                        child: Text('${product.name} (${product.spec}) - ¥${product.currentPrice}'),
                      );
                    }).toList(),
                  ),
                  const SizedBox(height: 16),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      IconButton(
                        icon: const Icon(Icons.remove),
                        onPressed: () {
                          if (quantity > 1) {
                            setState(() => quantity--);
                          }
                        },
                      ),
                      Container(
                        width: 60,
                        padding: const EdgeInsets.symmetric(vertical: 8),
                        decoration: BoxDecoration(
                          border: Border.all(color: Colors.grey),
                          borderRadius: BorderRadius.circular(4),
                        ),
                        child: Text(
                          quantity.toString(),
                          textAlign: TextAlign.center,
                          style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
                        ),
                      ),
                      IconButton(
                        icon: const Icon(Icons.add),
                        onPressed: () {
                          setState(() => quantity++);
                        },
                      ),
                    ],
                  ),
                  const SizedBox(height: 8),
                  Text(
                    '小计: ¥${subtotal.toStringAsFixed(2)}',
                    style: const TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.bold,
                      color: Colors.green,
                    ),
                  ),
                ],
              ),
              actions: [
                TextButton(
                  onPressed: () => Navigator.of(ctx).pop(),
                  child: const Text('取消'),
                ),
                ElevatedButton(
                  onPressed: selectedProduct == null ? null : () {
                    Navigator.of(ctx).pop();
                    _addProductToBill(selectedProduct!, quantity);
                  },
                  child: const Text('添加'),
                ),
              ],
            );
          },
        ),
      );
    } catch (e) {
      SnackbarHelper.showError(context, '加载商品失败: $e');
    }
  }
}